#!/usr/bin/python3
from openpyxl import load_workbook
import os, gc
from .Base_Plugin import Base_Plugin


class Sheet_Clear_Lookup_Unused(Base_Plugin):
    """清理未使用的数据字典组插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context
        self.inside_sheets = self.context["inside_sheets"]

    def get_lookup_type_set(self, sheet):
        """
        获取数据字典组的名称集合
        """
        _lookup_type_set = set()
        for row in sheet:
            if row[0].row < self.project_config["通用开始行"]:
                continue
            _lookup_type_set.add(row[0].value)
        return _lookup_type_set

    def disable_unused_lookup_type(self, sheet, lookup_names):
        """
        禁用未使用的数据字典项
        """
        for row in sheet:
            if row[0].row < self.project_config["通用开始行"]:
                continue
            if row[0].value in lookup_names:
                row[3].value = "N"

    def run(self, workspace, source):
        workbook = load_workbook(os.path.join(workspace, source))
        _directory = workbook["目录"]
        _lookup_type = workbook["数据字典组"]
        _lookup_type_set = self.get_lookup_type_set(_lookup_type)
        _used_lookup_type_set = set()

        for directory_row in _directory.rows:
            if directory_row[1].row < self.project_config["通用开始行"]:
                continue

            table_description = directory_row[2].value.strip()
            if table_description in workbook.sheetnames:
                sheet = workbook[table_description]
                for row in sheet.rows:
                    if row[1].row < self.project_config["列字段开始行"]:
                        continue
                    if (
                        len(
                            list(
                                filter(
                                    lambda item: item in row[6].value, _lookup_type_set
                                )
                            )
                        )
                        > 0
                    ):
                        _used_lookup_type_set.add(row[6].value.split("；")[1])

                self.processed += 1
        _unused_lookup_type_set = _lookup_type_set - _used_lookup_type_set
        self.disable_unused_lookup_type(_lookup_type, _unused_lookup_type_set)
        return_val = None
        if self.processed > 0:
            saved_name = r"ClearLookupUnused.xlsx"
            new_path = os.path.join(workspace, saved_name)
            if os.path.exists(new_path):
                os.remove(new_path)
            workbook.save(new_path)
            return_val = saved_name
        else:
            return_val = source
        del workbook
        gc.collect()
        return return_val
